import React, { useEffect, useRef, useState } from 'react';
import { Divider, Button, Popconfirm } from 'antd';
import { 
  getComplainCommucation, 
  replay as doReplay, 
  closeComplain,
  getComplainDetail } from '@/services/shop/api';
import { showMsg, MsgType, isExits } from '@/utils/utils';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import ReplayDialog from './ReplayDialog'
import { isExternal } from 'util/types';

const Commucation: React.FC<{complain_id: string;}> = (props) => {
  const { complain_id } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<any>[] = [
    {
      title: '时间',
      dataIndex: 'time',
      width: 180
    },
    {
      title: '发言人',
      dataIndex: 'speaker',
      width: 120
    },
    {
      title: '操作者/工号',
      width: 320,
      render: (dom, entity) => {
        if (entity.speaker === '客服') {
          return entity.oper_name + '/' + entity.oper_id
        }
        return entity.oper_name
      }
    },
    {
      title: '内容',
      dataIndex: 'content'
    }
  ]

  const [complainDetail, setComplainDetail] = useState<SHOPAPI.ShopComplaint>({} as SHOPAPI.ShopComplaint)

  const fetchComplainDetail = async () => {
    try {
      const data: SHOPAPI.ShopComplaint = await getComplainDetail(complain_id)
      setComplainDetail(data)
    } catch (error) {
      showMsg(error?.data?.errmsg)
    }
  }

  /**
   * 回复
   * @param fields 
   * @returns 
   */
   const replay = async (fields: any) => {
    try {
      fields = Object.assign({}, fields, { complain_id })
      await doReplay(fields)
      actionRef.current?.reload()
      return true
    } catch (error) {
      showMsg(error?.data?.errmsg)
      return false
    }
  };

  useEffect(() => {
    if (complain_id) {
      fetchComplainDetail()
    }
  }, [complain_id])

  useEffect(() => {
    const timer = setInterval(() => {
      fetchComplainDetail();
    }, 3000);

    return () => {
      clearInterval(timer);
    }
  }, [])
  

  return <div className="service-record">
     <div className="header">
        <div className="title">1.沟通记录</div>
        <div className="btns">
          投诉状态：{complainDetail.status === 'C' ? '已关闭' : '沟通中'}
        </div>
      </div>
      <Divider style={{margin: '10px 0'}} />
      <div>
        {
          complainDetail.status !== 'C' &&  <>
            {isExits('600612005') && <Button onClick={() => setVisible(true)} style={{marginRight: 10}} type="primary">添加回复</Button>}
            <Popconfirm onConfirm={async () => {
                try {
                  await closeComplain({
                    complain_id,
                    status: 'C'
                  })
                  showMsg('问题已关闭', MsgType.SUCCESS)
                  fetchComplainDetail()
                } catch (error) {
                  showMsg(error?.data?.errmsg)
                }
              }} title="关闭后无法在回复此问题，是否继续？" okText="确认关闭" cancelText="再想想">
              {isExits('600612004') && <Button type="primary">关闭投诉</Button>}
            </Popconfirm>  
          </>
        }
      </div>
      
      <ProTable<any> 
      bordered 
      actionRef={actionRef}
      rowKey="detail_id"
      polling={3000}
      search={false}
      rowClassName={(record) => {
        return record.speaker === '客服' ? 'new-add' : '';
      }}
      options={false}
      request={async (params) => {
        try {
          const data: any = await getComplainCommucation(complain_id);
          return {
            data: data,
            success: true,
            total: data.length
          };
        } catch (error) {
          showMsg(error?.data?.errmsg);
          return {
            data: [],
            success: true,
            total: 0
          };
        }
      }}
      pagination={false}
      columns={columns} />

      {
        visible && <ReplayDialog handleModalVisible={setVisible} handleAdd={replay}/>
      }
  </div>
}
export default Commucation;